/**
 * 
 */
package com.farkas.interceptors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import org.springframework.web.util.UrlPathHelper;

/**
 * @author farkas
 * 
 */
public class SecurityInterceptors extends HandlerInterceptorAdapter {

	private UrlPathHelper urlPathHelper = new UrlPathHelper();
	private PathMatcher pathMatcher = new AntPathMatcher();

	private String[] excludes;

	private String loginURL;

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.springframework.web.servlet.handler.HandlerInterceptorAdapter#preHandle
	 * (javax.servlet.http.HttpServletRequest,
	 * javax.servlet.http.HttpServletResponse, java.lang.Object)
	 */
	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		String url = urlPathHelper.getLookupPathForRequest(request);
		System.out.println("filter on url:" + url);

		if (!isExcluded(url)) {
			System.out.println("url not excluded, checking login...");
			/*if (session) {
				// User in "Login page"
				request.getRequestDispatcher(loginURL).forward(request,
						response);
				return false;
			} else {
				// User in other Pages except "Login page"
				return super.preHandle(request, response, handler);
			}*/
		}
		return super.preHandle(request, response, handler);
	}

	/**
	 * @return the excludes
	 */
	public String[] getExcludes() {
		return excludes;
	}

	/**
	 * @param excludes
	 *            the excludes to set
	 */
	public void setExcludes(String[] excludes) {
		this.excludes = excludes;
	}

	/**
	 * @return the loginURL
	 */
	public String getLoginURL() {
		return loginURL;
	}

	/**
	 * @param loginURL
	 *            the loginURL to set
	 */
	public void setLoginURL(String loginURL) {
		this.loginURL = loginURL;
	}

	/**
	 * @param url
	 * @return
	 */
	private boolean isExcluded(String url) {
		for (String exculde : excludes) {
			if (this.pathMatcher.match(exculde, url)) {
				return true;
			}
		}
		return false;
	}
}
